from website.mce.req import *
from utils.file_operation import load_json_to_dict,save_dict_to_json
from rj.request import RequestHanlder
import time
from logger.main import setup_logger,logger

setup_logger()
rj = RequestHanlder()
def discount_and_round(price, discount: float = 0.7):
    # 先打七折
    discounted_price = price * discount

    # 将结果转换为字符串以便处理第一位
    price_str = str(discounted_price)

    # 找到小数点的位置
    decimal_index = price_str.find('.')

    if decimal_index != -1:
        # 获取第一位小数
        first_decimal = int(price_str[decimal_index + 1])

        # 如果第一位小数大于等于5，向上取整；否则向下取整
        if first_decimal >= 5:
            rounded_price = int(discounted_price) + 1
        else:
            rounded_price = int(discounted_price)
    else:
        # 如果没有小数点，直接取整
        rounded_price = int(discounted_price)

    return rounded_price


if __name__ == "__main__":
    data_list = load_json_to_dict("des_list.json")
    for item in data_list:
        time.sleep(1)
        print(f"正在处理{item["code"]}")
        procode = procode_process(item["code"])
        prourl = search_procode(procode)
        
        try:
            if prourl:
                html = get_page_html(prourl)
                spu_list = get_spu_list(html)
                # print(spu_list)
                # 设置商品详情
                item["desc"] = get_prodes(html)
                for sku in item["skuInfos"]:
                    spec = sku["skuAttributes"][0]["attributeValue"].split("/")[0]
                    for spu_item in spu_list:
                        if spec == spu_item["spec"]:
                            print(f"匹配规格{spu_item["spec"]} 价格:{spu_item["price"]}")
                            # 设置商品折扣为0.85
                            sku["price"] = discount_and_round(int(spu_item["price"]), 0.85)
                            # 设置差异价为0.8
                            sku["differentPrices"][0]["price"] = discount_and_round(int(spu_item["price"]), 0.8)
                            
                res = rj.batchSaveOrUpdateProductV2([item])
                # save_dict_to_json(item,f"des_list_{item["code"]}.json")
                print(res.json())
            
            else:
                logger.error(f"商品搜索失败 {item["code"]},商品id为{item["skuInfos"][0]["id"]}")
                
        except Exception as e:
            logger.error(f"处理{item["code"]}失败,商品id为{item["skuInfos"][0]["id"]}")
    